<?php

namespace App\Http\Controllers\Admin\Good;

use App\Http\Controllers\Admin\BaseAdminController;
use App\Models\CollectionGoods;
use App\Models\Exchanges;
use App\Models\GoodComments;
use App\Models\Goods;
use App\Models\Shops;
use App\Models\Users;
use App\Models\UploadedFile;
use App\Models\Acategory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

/**
 * 店铺控制器
 *
 * @author lxp
 * @package App\Http\Controllers\Shops
 */
class GoodsController extends BaseAdminController
{
    private $tree;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商品列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20200318
     */
    public function index()
    {
        // 处理排序
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = Goods::orderBy($sort, $order)->where('status','!=',0);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } elseif (is_mobile(request('title'))) {
                $query->where('phone', request('title'));
            } else {
                $query->where('username', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $shops = $query->select([
            'id',
            'default_img',
            'views',
            'title',
            'comments',
            'status',
            'is_recommend',
            'created_at'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $shops->appends(app('request')->all());

        return view('admin.good.goods', [
            'goods' => $shops,
        ]);
    }
    /**
     * 商品列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20200318
     */
    public function goodshen()
    {
        // 处理排序
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = Goods::orderBy($sort, $order)->where('status',0);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } elseif (is_mobile(request('title'))) {
                $query->where('phone', request('title'));
            } else {
                $query->where('username', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $shops = $query->select([
            'id',
            'default_img',
            'views',
            'title',
            'comments',
            'status',
            'is_recommend',
            'created_at'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $shops->appends(app('request')->all());

        return view('admin.good.goodshen', [
            'goods' => $shops,
        ]);
    }
    /**
     * 添加用户
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170825
     */
    public function add()
    {
        $this->setTree();
        $shops = Shops::where('status', 1)->orderBy('id')->get()->toArray();
        return view('admin.good.goods_form', ['shops' => $shops, 'cates' => $this->tree->getOptions(2)]);
    }

    /**
     * 取得并初始化分类数据
     *
     * @author lxp 20160706
     */
    private function setTree()
    {
        // 取得分类
        $cates = Acategory::orderBy('sort_order')->orderBy('cate_id')->get()->toArray();
        // 处理分类结构
        $this->tree = app('tree');
        $this->tree->setTree($cates, 'cate_id', 'parent_id');
    }

    /**
     * 编辑用户
     *
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170111
     */
    public function edit($id)
    {
        // 取得用户信息
        $user = Goods::findOrFail($id);
        $this->setTree();
        $shops = Shops::where('status', 1)->orderBy('id')->get()->toArray();
        return view('admin.good.goods_form', [
            'shops' => $shops, 'cates' => $this->tree->getOptions(2),
            'user' => $user
        ]);
    }

    /**
     * 编辑用户
     *
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20200327
     */
    public function shen($id)
    {
        // 取得用户信息
        $user = Goods::findOrFail($id);
        $this->setTree();
        $shops = Shops::where('status', 1)->orderBy('id')->get()->toArray();
        return view('admin.good.goods_shen', [
            'shops' => $shops, 'cates' => $this->tree->getOptions(2),
            'user' => $user
        ]);
    }

    /**
     * 保存商品
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20200327
     */
    public function save()
    {

        // 保存用户信息
        DB::transaction(function () {

            $rule = [

            ];
            if (!request('id')) {
                $rule = array_merge([
                    'title' => 'required|unique:goods,title,' . request('id') . ',id',
                    'address' => 'required|',
                    'default_img' => 'required|',
                    'shop_id' => 'required|',
                    'cate_id' => 'required|',
                    'content' => 'required|',

                ], $rule);
            }

            $this->validate(request(), $rule, [], [
                'title' => '商品名称',
                'address' => '商品地址',
                'shop_id' => '店铺',
                'default_img' => '商品图片',
                'cate_id' => '商品分类',
                'content' => '商品详情',

            ]);
            $user = Goods::findOrNew(request('id'));
            $user->title = request('title');
            $exhibit_num_json = [];
            $shops = Shops::where('id', request('shop_id'))->first();
            $user->shop_name = $shops->title;
            $user->sign = request('sign');
            $img = request('default_img');

            $default_img = $img;
            $size_name_arr = request('size_name');
            $size_num_arr = request('size_num');
            $total = 0;
            foreach ($size_name_arr as $k => $g) {
                $exhibit_num_json[] = [
                    'size_name' => $g,
                    'size_num' => $size_num_arr[$k],

                ];
                $total=intval($total) +intval($size_num_arr[$k]);
            }
            $user['sizes'] = json_encode($exhibit_num_json);
            $user->shop_id = request('shop_id');
            $user->cate_id = request('cate_id');
            $user->address = request('address');
            $user->total =$total;
            $user->is_recommend = request('is_recommend');
            $user->send_type = request('send_type',1);
            $user->is_top = request('is_top');
            $user->default_img = $default_img;
            $user->content = request('content');
            $user->save();
            // 更新附件id
            if (!request('id')) {
                // 更新店铺图片
                if (intval(request('file_id'))) {
                    UploadedFile::where('file_id', intval(request('file_id')))->update(['item_id' => $user->id]);
                }

            }
        });

        return $this->success(get_session_url('index'));
    }

    /**
     * 删除用户
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author lxp 20160713
     */
    public function delete($id)
    {
        if (request()->ajax() && intval($id)) {
            // 判断用户是否可以被删除
            // 删除用户
            Goods::destroy($id);
            CollectionGoods::where('good_id',$id)->delete();
            Exchanges::where('good_id',$id)->delete();
            return $this->success();
        }
    }
    /**
     * 评论列表
     *
     * @param int $id 商品id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20160713
     */
    public function comments(){
        // 取得评论列表
        $sort = request('sort', 'id');
        $order = request('order', 'desc');

        $query = GoodComments::orderBy($sort, $order);
        if (request('title')) {
            if (request('title')) {
                $query->where('title', 'LIKE', "%" . request('title') . "%");
            } else {
                $query->where('nickname', 'LIKE', "%" . request('title') . "%");
            }
        }
        // 发布时间时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }

        $id= request('id');
        // 取得列表
        $query->where('goods_id',$id);
        $forums = $query->select([
            'id',
            'avatar',
            'content',
            'nickname',
            'goods_id',
            'status',
            'created_at'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $forums->appends(app('request')->all());

        return view('admin.good.comments', [
            'forums' => $forums,
            'id'=>$id,
        ]);

    }
    public function comment_add($id)
    {
        // 取得用户信息
        $user = Goods::findOrFail($id);

        return view('admin.good.comments_form', [
            'forums' => $user,
            'id'=>$id
        ]);
    }
    public function comment_save()
    {
        // 取得用户信息
        $id = request('id');
        $user = GoodComments::findOrNew($id);
        $user->uid = Auth::user()->uid;
        $uinfo = Users::where('uid', Auth::user()->uid)->select('uid', 'nickname', 'avatar')->first();
        $user->avatar =get_file_url($uinfo ->avatar);
        $user->nickname =$uinfo ->nickname;
        $user->imgs =request('imgs');
        $user->content = request('content');
        $user->goods_id = request('goods_id');
        $user->status = 0;
        $user->save();
//        Shops::where('id',request('shop_id'))->increment('comment_num');
        return $this->success(get_session_url('index'));
    }
    /**
     * 删除用户
     *
     * @author lxp 20160713
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function comment_delete($id)
    {
        if (request()->ajax() && intval($id)) {
            // 判断用户是否可以被删除
            // 删除用户
            GoodComments::destroy($id);
            return $this->success();
        }
    }
    /**
     * 审核评论
     *
     * @author yh 20170111
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function comment_shen($id)
    {
        // 取得用户信息
        $user = GoodComments::findOrFail($id);
        $users = Goods::findOrFail($user->goods_id);

        return view('admin.good.comments_shen', [
            'user' => $user,
            'users' =>$users
        ]);
    }
    /**
     * 商品推荐首页
     *  @api changeShop
     * @apiParams id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200406
     *
     **/
    public function recommend($id){
        $shop = Goods::where('id',$id)->first();
        $status = $shop->is_recommend;
        if($status==0){
            $shop->is_recommend=1;
            $shop->status=1;
        }else{
            $shop->is_recommend=0;
        }
        $shop->save();
        return $this->success();
    }

    /**
     * 评论审核
     *
     * @author yh 20200322
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function comment_refund()
    {
        $user = GoodComments::findOrNew(request('id'));
        $user -> status =intval(request('status'));
        $rule = [];
        if(request('status')==0){
            $rule = array_merge([
                'refund_msg' => 'required'
            ], $rule);
            $this->validate(request(), $rule, [], [
                'refund_msg'=>'审核不通过原因',
            ]);
        }
        $user -> refund_msg = request('refund_msg');
        $user->save();
        Goods::where('id',$user->goods_id)->increment('comments');
        return $this->success(get_session_url('index'));
    }
    /**
     * 删除用户
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author lxp 20160713
     */
    public function change($id)
    {
        $goods = Goods::where('id', $id)->first();
        if ($goods->status == 2) {
            $goods->status = 1;
        } else {
            $goods->status = 2;
        }
        $goods->save();
        return $this->success();
    }

    /**
     * 审核商品
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200327
     */
    public function refund()
    {
        $user = Goods::findOrNew(request('id'));
        $user->status = request('status');
        $rule = [];
        if (request('status') == 2) {
            $rule = array_merge([
                'refund_msg' => 'required'
            ], $rule);
            $this->validate(request(), $rule, [], [
                'refund_msg' => '审核不通过原因',
            ]);
        }
        $user->refund_msg = request('refund_msg');

        $user->save();
        return $this->success(get_session_url('index'));
    }
}